<template>
  <div>
    <div class="biz-goods">

      <div class="goods-left-scroll">
        <div class="goods-left">
          <!--<div class="goods-left__item active"><span>热销榜</span></div>-->
          <template v-for="(item,index) in goods">
            <div class="goods-left__item"
                 @click="selectItem($event, index)"
                 ref="goods-left-hook"
                 :class="{active:index==currentIndex}">
              <span v-if="item.count" class="num"><van-tag round type="danger">{{ item.count }}</van-tag></span>
              <span class="text-center">{{ item.name }}</span>
            </div>
          </template>
        </div>
      </div>

      <div class="goods-right-scroll">
        <div class="goods-right">
          <div v-for="(item, index) in goods" ref="goods-panel-hook" class="goods-panel ">
            <div class="goods-panel__title" :style="{'opacity': index}">{{ item.name }}</div>
            <div v-for="(foods, foodsIndex) in item.foods" class="goods-panel__item">
              <van-image class="goods-img" fit="contain"
                         :src="foods.icon"></van-image>
              <div class="goods-cont flex-sub padding-left-sm">
                <div class="goods-title">{{ foods.name }}</div>
                <div class="goods-desc text-999">{{ foods.description }}</div>
                <div class="goods-sell flex text-999">
                  <p>月售{{ foods.sellCount }}份</p>
                  <p class="padding-left-sm" v-if="foods.rating">好评率{{ foods.rating }}%</p>
                </div>
                <div class="flex justify-between align-center">
                  <div>
                    <span class="price">￥{{ foods.price }}</span>
                    <span class="old-price">{{ foods.oldPrice ? '￥' + foods.oldPrice : '' }} </span>
                  </div>
                  <div>
                    <div @click="addCart($event, index, foodsIndex)" class="ok-inline-block">
                      <van-icon color="#1989fa" size="24" name="add"/>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="goods && goods.length" class="goods-panel__fixed">{{ goods[currentIndex].name }}</div>
      </div>

    </div>
    <ShopCar :select-foods="selectFoods" ref="shopCart"></ShopCar>
  </div>
</template>

<script type="es6">
import {elemGoods} from "@/api/elem";
import ShopCar from "@/components/elem/ShopCar.vue"

export default {
  inject: ['reload'], /**reload(callback);对应provide中的数组值*/
  name: "goods",
  components: {ShopCar},
  data() {
    return {
      goods: "",
      scrollRight: "",
      scrollLeft: "",
      listHeight: [],//存储元素高度
      scrollY: 0,
      balls: [{show: false}, {show: false}, {show: false}, {show: false}, {show: false}],
      dropBall: [], // 用dropBalls来存放掉落的小球
    }
  },
  computed: {
    currentIndex() {
      if (this.scrollY >= this.listHeight[1]) {
        for (let i = 0; i < this.listHeight.length; i++) {
          let h1 = this.listHeight[i];
          let h2 = this.listHeight[i + 1];
          //这里减去5为了去除位置差异
          if (!h2 || (this.scrollY > h1 - 5 && this.scrollY <= h2 - 5)) {
            //设置左侧菜单高亮显示
            return i >= this.listHeight.length - 1 ? i - 1 : i;
          }
        }
      }
      return 0;
    },

    selectFoods() {
      let foods = [];
      if(this.goods){
        this.goods.forEach((good, index) => {
          good.foods.forEach(food => {
            if(food.count){
              foods.push(food);
            }
          });
        });
      }
      return foods
    },
  },
  async mounted() {
    this.$loading();
    let res = await elemGoods();
    console.log('res', res);
    if (200 == res.code) {
      this.$loadinghide();
      this.goods = res.data;
      this.$nextTick(() => {
        this._scrollInit();
        this._itemHeight();
      });
    }
  },
  methods: {
    _drop (target) { // 在goods.vue定义 _drop方法将cartcontrol的传递过来target对象再传递给shopCart
      this.$nextTick(() => { // 使用$nextTick优化体验
        this.$refs.shopCart.drop(target) // 父组件goods通过.$refs属性访问shopCart子组件的drop方法
      });
    },

    // addCart添加事件
    addCart(event, index, foodsIndex) {
      if (!event._constructed) return;
      this._drop(event.target);
      //this.$emit('cart-add', event.target); // 向父组件触发一个自定义的cart-add事件，同时将事件对象传递给父组件
      let goods = this.goods;
      let count = goods[index].foods[foodsIndex].count; //单个商品选择数量
      let counts = goods[index].count;  //某项商品选择数量
      if (count === undefined || count === null) {
        this.$set(this.goods[index].foods[foodsIndex], "count", 1);
      } else {
        this.goods[index].foods[foodsIndex].count = count + 1;
      }
      if (counts == undefined) {
        this.$set(this.goods[index], "count", 1);
      } else {
        counts = 0;
        goods[index].foods.forEach((item, cindex) => {
          if (item.count === undefined || item.count === null) {
            this.$set(this.goods[index].foods[cindex], "count", 0);
          } else {
            counts += item.count;
          }
        });
        this.goods[index].count = counts;
      }
    },

    selectItem(e, index) {
      if (!e._constructed) return;//避免pc派发两次事件
      let goodsPanelList = this.$refs['goods-panel-hook'];
      let el = goodsPanelList[index];
      this.scrollRight.scrollToElement(el, 300);
    },

    _scrollInit() {
      this.scrollLeft = new BScroll(".goods-left-scroll", {
        click: true
      });
      this.scrollRight = new BScroll(".goods-right-scroll", {
        click: true,
        probeType: 3
      });
      this.scrollRight.on('scroll', (pro) => {
        this.scrollY = Math.abs(Math.round(pro.y));
        //控制左边菜单自动滚动
        if (this.currentIndex < 3) {
          let el = (this.$refs['goods-left-hook'])[0];
          this.scrollLeft.scrollToElement(el, 300);
        } else if (this.currentIndex % 3 == 0) {
          let el = (this.$refs['goods-left-hook'])[this.currentIndex - 3];
          this.scrollLeft.scrollToElement(el, 300);
        }
      });
    },

    _itemHeight() {
      let goodsPanelList = this.$refs['goods-panel-hook'];
      let tempHeight = 0;
      let listHeight = [tempHeight];
      goodsPanelList.forEach(item => {
        tempHeight += item.clientHeight;
        listHeight.push(tempHeight);
      });
      this.listHeight = listHeight;
    }
  }
}
</script>

<style lang="scss" scoped>
$--main: #1989fa;
$bg-gradient: linear-gradient(90deg, #fc9153, #f01414);
$goods-price: #FB543B;
.biz-goods {
  position: relative;
  z-index: 19;
  background: #FFFFFF;
  height: calc(100vh - 40px);
  padding-bottom: 60px;
  /*position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 236px;*/
  overflow: hidden;
  display: flex;

  .goods-left {
    width: 96px;
    background: #f3f5f7;
    height: auto;
    display: block;
    position: relative;
    color: #666666;

    .goods-left__item {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      height: 56px;
      padding: 0 10px;
      position: relative;

      .num {
        position: absolute;
        right: 5px;
        top: 3px;
        display: block;

        .van-tag {
          background: $bg-gradient;
          border-radius: 16px;
          color: #fff;
          display: inline-block;
          font-size: 10px;
          font-weight: 700;
          height: 16px;
          line-height: 16px;
          padding: 0 5px;
          text-align: center;
        }
      }

      &.active {
        background: #FFFFFF;
      }
    }
  }

  .goods-right-scroll {
    flex: 1;
    position: relative;

    .goods-right {
      background: #FFFFFF;
      height: auto;
      display: block;
    }

    .goods-panel__fixed {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
    }

    .goods-panel__fixed,
    .goods-panel__title {
      background: #f3f5f7;
      border-left: 2px solid #d9dde1;
      color: #666;
      font-size: 14px;
      height: 32px;
      line-height: 32px;
      padding-left: 14px;
    }

    .goods-panel__item {
      padding: 15px;
      display: flex;

      .goods-img {
        width: 64px;
        height: 52px;
        overflow: hidden;
      }

      .goods-title {
        font-size: 16px;
        margin: 2px 0 5px;
      }

      .goods-desc {
        font-size: 12px;
        margin-bottom: 5px;
      }

      .goods-sell {
        margin-bottom: 5px;
        font-size: 12px;
      }

      .price {
        color: $goods-price;
        font-size: 16px;
        font-weight: bold;
      }

      .old-price {
        color: #999999;
        font-size: 12px;
        display: inline-block;
        padding-left: 5px;
        text-decoration: line-through;
      }

    }
  }
}

.ball-container {
  .ball {
    position: fixed;
    left: 32px;
    bottom: 22px;
    z-index: 900;
    transform: translate3d(0, 0, 0);
    //transition: all 0.6s cubic-bezier(0.49, -0.29, 0.75, 0.41) ;
    transition: all 0.6s cubic-bezier(0.49, -0.29, 0.75, 0.41);

    .inner-hook {
      width: 16px;
      height: 16px;
      border-radius: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
      color: #FFFFFF;
      font-weight: bolder;
      background: rgb(0, 160, 220);
      transition: all 0.6s linear;
      transform: translate3d(0, 0, 0);
    }
  }
}
</style>